#include "../server.hpp"

// void HandeRead(Channel* channel){
//     int fd = channel->Fd();
//     char buf[1024] = {0};
//     int ret = recv(fd,buf,1023,0);
//     if(ret <= 0){
//         return HandeClose(channel);
//     }
//     DBG_LOG("%s",buf);
//     channel->EnableWrite();
// }
// void HandeWrite(Channel* channel){
//     int fd = channel->Fd();
//     const char* data = "监听些时间";
//     int ret = send(fd,data,strlen(data),0);
//     if(ret < 0){
//         channel->Remove();
//         HandeClose(channel);
//     }
//     channel->DisableWrite(); // 无数据发送，需要关闭监控
// }

// std::vector<LoopThread> threads(2);
// int next_Loop = 0;

std::unordered_map<uint64_t,PtrConnection> _conns; // 管理所有的连接对象
EventLoop base_loop;
LoopThreadPool* loop_pool;
void ConnectDestroy(const PtrConnection& conn){
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn){
    DBG_LOG("NEW CONNECTION: %p",conn.get());
}

void OnMessage(const PtrConnection& conn,Buffer* buf){
    DBG_LOG("%s",buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "hello world";
    conn->Send(str.c_str(),str.size());
    conn->Shutdown();
}
uint64_t conn_id = 0;
void newConnection(int fd){
    PtrConnection conn(new Connnection(loop_pool->NextLoop(),conn_id,fd));
    conn->SetMessageCallback(std::bind(OnMessage,std::placeholders::_1,std::placeholders::_2));
    conn->SetSvrClosedCallback(std::bind(ConnectDestroy,std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->EnableInactiveRealse(10); // 非活跃超时销毁
    conn->Established(); // 就绪初始化
    _conns.insert({conn_id,conn});
    conn_id++;
    DBG_LOG("NEW THREAD---------------");
}

int main(int argc, char const *argv[])
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&base_loop,8085);
    acceptor.SetAcceptCallback(std::bind(newConnection,std::placeholders::_1));
    acceptor.Listen();
    base_loop.Start();
    return 0;
}
